﻿

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Threading;
using System.Configuration;

namespace EmailTask
{
    class Program
    {
        public static readonly NLog.Logger log = NLog.LogManager.GetLogger("emailtask");

        static System.Timers.Timer aTimer;
        static void Main(string[] args)
        {
            log.Info("程序启动");
            SetConsoleCtrlHandler(NewDelegate, true);
            aTimer = new System.Timers.Timer();

            aTimer.Elapsed += new ElapsedEventHandler(TimerOp); //到达时间的时候执行事件；

            int interval = 60;

            if (ConfigurationManager.AppSettings["Interval"] !=null) {
                int.TryParse(ConfigurationManager.AppSettings["Interval"],out interval);

               }



            aTimer.Interval = 1000* interval;
            aTimer.AutoReset = true;//设置是执行一次（false）还是一直执行(true)；
            aTimer.Enabled = true; //是否执行System.Timers.Timer.Elapsed事件；



            aTimer.Start();
            Console.ReadKey();

        }



        static public void TimerOp(object source, System.Timers.ElapsedEventArgs e)
        {
            log.Info("开始接收邮件");
           var lt= ReceiveEmailHelper.ReceiveEmail();

            foreach (var email in lt)
            {
                Console.Write(email.Address);
                log.Info("邮箱地址："+ email.NickName+ "        "+ email.Address +email.Content );
            }




            log.Info("接收完毕");
        }

        static public void TimerOpTest(object source, System.Timers.ElapsedEventArgs e)
        {
            log.Info("开始读取邮件");
            log.Info("邮件处理中");
            log.Info("处理完毕");
        }




        public delegate bool ControlCtrlDelegate(int ctrlType);
        private static readonly ControlCtrlDelegate NewDelegate = HandlerRoutine;

        [DllImport("kernel32.dll")]
        private static extern bool SetConsoleCtrlHandler(ControlCtrlDelegate handlerRoutine, bool add);

        public static bool HandlerRoutine(int ctrlType)
        {
            switch (ctrlType)
            {
                case 0:
                    aTimer.Stop();
                    log.Info("程序关闭"); //Ctrl+C关闭  
                    break;
                case 2:
                    aTimer.Stop();
                    log.Info("程序关闭"); //按控制台关闭按钮关闭  
                    break;
            }
            return false;
        }












    }



}
